package com.yuanfeng.userms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.LimitUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.dto.IntegralDetailDTO;
import com.yuanfeng.userms.entity.UserPointsLogEntity;
import com.yuanfeng.userms.feign.BaseServiceClient;
import com.yuanfeng.userms.mapper.UserPointsLogMapper;
import com.yuanfeng.userms.service.UserInfoService;
import com.yuanfeng.userms.service.UserPointsLogService;
import com.yuanfeng.userms.vo.IntegralValueListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class UserPointsLogServiceImpl extends ServiceImpl<UserPointsLogMapper, UserPointsLogEntity>
    implements UserPointsLogService{

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Override
    public ResponseResult queryLoginExit(Map<String, String> map) {
        QueryWrapper<UserPointsLogEntity> queryWrapper = new QueryWrapper<>();

        if (null != map && null != map.get("userId")) {
            queryWrapper.eq("user_id", map.get("userId").toString());
        }
        if (null != map && null != map.get("classId")) {
            queryWrapper.eq("class_id", "2");
        }
        if (null != map && null != map.get("startTime") && null != map.get("endTime")) {
            queryWrapper.between("points_log_time", map.get("startTime").toString(), map.get("endTime").toString());
        }

        UserPointsLogEntity userPointsLogEntity = this.baseMapper.selectOne(queryWrapper);

        return ResponseResult.success(userPointsLogEntity);
    }

    @Override
    public ResponseResult insertByMap(Map<String, Object> map) {
        UserPointsLogEntity entity = JSON.parseObject(JSON.toJSONString(map), UserPointsLogEntity.class);
        this.baseMapper.insert(entity);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryIntegralDetailList(Map<String, Object> params) {
        String token = params.get("token").toString();
        if (!RedisUtil.exists(YFConfig.YF_USER_TOKEN_USER + token)) {
            return ResponseResult.fail(BizCodeEnume.INTEGRAL_DETAIL_MUST_LOGIN);
        }


        // 获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);


        IntegralDetailDTO integralDetailDto = new IntegralDetailDTO();
        params.put("userId", userInfo.getUserId());
        //根据userid获取交易明细
        PageUtils pageInfoS = integralDetail(params);

        List<UserPointsLogEntity> logEntityList = (List<UserPointsLogEntity>) pageInfoS.getList();

        for (UserPointsLogEntity udbUcenterPointsLog : logEntityList) {
            if (udbUcenterPointsLog.getPointsLogType() == 2) {
                String s = "-" + udbUcenterPointsLog.getPointsLogPoints();
                udbUcenterPointsLog.setIntegralChange(s);
            } else {
                String s = "+" + udbUcenterPointsLog.getPointsLogPoints();
                udbUcenterPointsLog.setIntegralChange(s);
            }
        }

        pageInfoS.setList(logEntityList);

        //根据userid获取会员积分
        Integer integral = userInfoService.getById(userInfo.getUserId()).getUserIntegral();

        //查询积分规则
        ResponseResult resultResp = baseServiceClient.queryIntegralRules();
        Map<String, Integer> integralRules = (Map<String, Integer>) resultResp.getData();

        integralDetailDto.setLoginIntegral(integralRules.get("ruleLogin"));
        integralDetailDto.setRegisterIntegral(integralRules.get("ruleRegister"));
        integralDetailDto.setRuleConsume(integralRules.get("ruleConsume"));
        integralDetailDto.setCountIntegral(integral);
        integralDetailDto.setPageInfoS(pageInfoS);
        return ResponseResult.success(integralDetailDto);
    }

    @Override
    public ResponseResult query(Map<String, Object> params) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(params.get("token").toString());
        if (null != userInfo) {
            if (LimitUtils.checkLimit("integral", userInfo)) {
                //分页查询数据
                IPage<IntegralValueListVO> page = this.baseMapper.queryIntegralValueListPort(new Query<IntegralValueListVO>().getPage(params), params);
                List<IntegralValueListVO> records = page.getRecords();
                for (IntegralValueListVO record : records) {
                    //拼接积分类型
                    if (null != record.getPointsLogType() && record.getPointsLogType() == 1) {
                        record.setPointsLogPoints2("+" + record.getPointsLogPoints());
                    } else {
                        record.setPointsLogPoints2("-" + record.getPointsLogPoints());
                    }
                }
                page.setRecords(records);
                return ResponseResult.success(PageUtils.getPage(page));
            }else {
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    public PageUtils integralDetail(Map<String, Object> params) {

        IPage<UserPointsLogEntity> page = this.baseMapper.selectPage(new Query<UserPointsLogEntity>().getPage(params), new LambdaQueryWrapper<UserPointsLogEntity>()
                .eq(UserPointsLogEntity::getUserId, params.get("userId").toString())
                .eq(params.get("classId") != null && !"".equals(params.get("classId")), UserPointsLogEntity::getClassId, params.get("classId"))
                .ge(params.get("startTime") != null && !"".equals(params.get("startTime")), UserPointsLogEntity::getPointsLogTime, params.get("startTime"))
                .le(params.get("endTime") != null && !"".equals(params.get("endTime")), UserPointsLogEntity::getPointsLogTime, params.get("endTime"))
                .like(params.get("describe") != null && !"".equals(params.get("describe")), UserPointsLogEntity::getPointsLogOperate, params.get("describe"))
                .orderByDesc(UserPointsLogEntity::getPointsLogTime));
        return PageUtils.getPage(page);
    }
}




